﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace ProductCollector {
    public class WalterDrakeSearcher : ISiteSearcher
    {
        public const string SEARCH_URL = "http://search.wdrake.com/search?p=Q&ts=custom&w={0}&srt={1}";
        public const string HOME_URL = "http://search.wdrake.com";
        public IList<Product> Search(SearchCriteria criteria) {
            var web = new HtmlWeb();
            string url = string.Format(SEARCH_URL, criteria.SearchValue, criteria.CurrentPageIndex * criteria.NumOfProduct);
            List<Product> result = new List<Product>();

            HtmlDocument doc = web.Load(url);
            var gridNode = doc.DocumentNode.SelectSingleNode("//div[@id='internalContentWrapper']");
            if (gridNode == null) {
                return result;
            }
            var allProds = gridNode.SelectNodes("./div[contains(@class,'sli_grid')]");

            foreach (HtmlNode node in allProds) {
                Product p = GetProductByNode(node);
                if (p != null) {
                    result.Add(p);
                }
                if (result.Count >= criteria.NumOfProduct) {
                    break;
                }
            }
            return result;
        }
        private Product GetProductByNode(HtmlNode liNode) {
            Product p = new Product();
            var atopLink = liNode.SelectSingleNode("./a");
            if (atopLink != null) {
                p.OriginalUrl = atopLink.GetAttributeValue("href", HOME_URL);
                var img = atopLink.SelectSingleNode("./img");
                if (img != null) {
                    p.ThumbImg = img.GetAttributeValue("src", HOME_URL);
                }
            }
            var title = liNode.SelectSingleNode("./div[contains(@class,'sli_details')]/h3/a");
            if (title != null) {
                p.ProductName = title.InnerText;
            }
            var price = liNode.SelectSingleNode("./div[contains(@class,'sli_details')]/span[contains(@class,'sli_price')]");
            
            if (price != null) {
                p.FormattedPrice = price.InnerText;
            }

            return p;
        }
        public int CountProduct(SearchCriteria criteria) {
            throw new NotImplementedException();
        }
    }
}
